package org.jeecg.modules.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.oms.entity.DesignFile;
import org.jeecg.modules.oms.entity.ProductSalesOrder;
import org.jeecg.modules.oms.entity.XingeProfileCutDetail;
import org.jeecg.modules.oms.entity.XingeProfileMaterial;
import org.jeecg.modules.oms.service.IDesignFileService;
import org.jeecg.modules.oms.service.IProductSalesOrderService;
import org.jeecg.modules.oms.service.IXingeProfileCutDetailService;
import org.jeecg.modules.oms.service.IXingeProfileMaterialService;
import org.jeecg.modules.oms.parser.OptimizationFileProcessor;
import org.jeecg.modules.oms.parser.OptimizationFileProcessorFactory;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysEmployee;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysEmployeeService;
import org.jeecg.modules.oms.vo.SummaryFileParseResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设计文件控制器
 */
@RestController
@RequestMapping("/oms/designFile")
@Slf4j
public class DesignFileController {

    @Autowired
    private IDesignFileService designFileService;

    @Autowired
    private IProductSalesOrderService productSalesOrderService;

    @Autowired
    private ISysEmployeeService sysEmployeeService;

    @Autowired
    private OptimizationFileProcessorFactory optimizationFileProcessorFactory;
    
    @Autowired
    private IXingeProfileMaterialService xingeProfileMaterialService;
    
    @Autowired
    private IXingeProfileCutDetailService xingeProfileCutDetailService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 根据订单ID获取设计文件信息
     */
    @AutoLog(value = "设计文件-根据订单ID获取")
    @GetMapping("/getByOrderId")
    public Result<DesignFile> getByOrderId(@RequestParam(name = "orderId") String orderId) {
        DesignFile designFile = designFileService.getByOrderId(orderId);
        return Result.OK(designFile);
    }

    /**
     * 上传汇总单
     */
    @AutoLog(value = "设计文件-上传汇总单")
    @PostMapping("/uploadSummaryFile")
    public Result<Boolean> uploadSummaryFile(@RequestParam(name = "orderId") String orderId,
                                           @RequestParam(name = "file") MultipartFile file,
                                           @RequestParam(name = "uploadPersonId", required = false) String uploadPersonId,
                                           @RequestParam(name = "uploadPersonName", required = false) String uploadPersonName) {
        boolean success = designFileService.uploadSummaryFile(orderId, file, uploadPersonId, uploadPersonName);
        if (success) {
            return Result.OK( "汇总单上传成功");
        } else {
            return Result.error("汇总单上传失败");
        }
    }

    /**
     * 处理优化单上传（支持单个订单和合单）
     * 
     * @param orderId 单个订单ID（可选）
     * @param orderIds 多个订单ID，逗号分隔（可选）
     * @param file 优化单文件
     * @param request 请求对象
     * @return 处理结果
     */
    @AutoLog(value = "上传优化单")
    @ApiOperation(value = "上传优化单", notes = "上传优化单，支持单个订单和合单")
    @PostMapping(value = "/uploadOptimization")
    public Result<?> uploadOptimization(@RequestParam(name = "orderId", required = false) String orderId,
                                       @RequestParam(name = "orderIds", required = false) String orderIds,
                                       MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            return Result.error("未上传文件");
        }
        
        // 获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        String userName = sysUser.getRealname();
        
        // 处理订单ID参数
        List<String> orderIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(orderIds)) {
            // 合单模式：解析多个订单ID
            orderIdList = Arrays.asList(orderIds.split(","));
            log.info("合单优化上传，订单ID列表：{}", orderIdList);
        } else if (StringUtils.isNotBlank(orderId)) {
            // 单个订单模式
            orderIdList.add(orderId);
            log.info("单个优化单上传，订单ID：{}", orderId);
        } else {
            return Result.error("请提供订单ID参数");
        }
        
        // 验证所有订单是否存在并获取优化软件类型
        List<ProductSalesOrder> orders = new ArrayList<>();
        Integer optimizeSoftwareType = null;
        Integer windowDoorType = null;
        
        for (String id : orderIdList) {
            ProductSalesOrder order = productSalesOrderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在：" + id);
            }
            
            // 验证优化软件类型一致性（合单时必须相同）
            if (optimizeSoftwareType == null) {
                optimizeSoftwareType = order.getOptimizationSoftwareType();
            } else if (!optimizeSoftwareType.equals(order.getOptimizationSoftwareType())) {
                return Result.error("合单上传时，所有订单的优化软件类型必须一致");
            }

            if(windowDoorType ==null){
                windowDoorType = order.getWindowDoorType();
            }else {
                if(!windowDoorType.equals(order.getWindowDoorType())){
                    return Result.error("合单上传时，所有订单的门窗生产类型必须一致");
                }
            }
            orders.add(order);
        }
        
        // 使用工厂获取对应的处理器，新格尔软件时根据门窗类型细分
        OptimizationFileProcessor processor = optimizationFileProcessorFactory.getProcessor(optimizeSoftwareType.toString(), windowDoorType);
        
        boolean allSuccess = true;
        Map<String, Object> result = new HashMap<>();
        List<XingeProfileMaterial> allProfileMaterials = new ArrayList<>();
        //list转String  逗号间隔
        String orderIdsStr = orderIdList.stream().collect(Collectors.joining(","));
        boolean success = processor.processOptimizationFile(orderIdsStr, file, userId, userName,orders);
        for (String id : orderIdList) {
            // 如果是新格尔-窗优化软件类型，收集型材清单数据
            if (optimizeSoftwareType == 1 && windowDoorType == 0) {
                List<XingeProfileMaterial> profileMaterials = xingeProfileMaterialService.getByOrderId(id);
                allProfileMaterials.addAll(profileMaterials);
            }
        }
        
        if (success) {
            if (optimizeSoftwareType == 1 && !allProfileMaterials.isEmpty()) {
                result.put("profileMaterials", allProfileMaterials);
                log.info("返回合并的型材清单数据，总数量: {}", allProfileMaterials.size());
            }
            
            String message = orderIdList.size() > 1 ? 
                String.format("合单优化上传成功，共处理%d个订单", orderIdList.size()) : "优化单上传成功";
            result.put("message", message);
            return Result.OK(result);
        } else {
            return Result.error("部分或全部订单处理失败");
        }
    }

    /**
     * 获取最近上传的设计文件
     */
    @AutoLog(value = "设计文件-获取最近上传的设计文件")
    @GetMapping("/getRecentFiles")
    public Result<List<DesignFile>> getRecentFiles(
            @RequestParam(name = "limit", defaultValue = "10") Integer limit,
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "fileType", required = false) String fileType,
            @RequestParam(name = "uploadPerson", required = false) String uploadPerson,
            @RequestParam(name = "beginDate", required = false) String beginDate,
            @RequestParam(name = "endDate", required = false) String endDate) {
        
        log.info("获取最近设计文件，参数: limit={}, orderNo={}, fileType={}, uploadPerson={}, beginDate={}, endDate={}", 
                limit, orderNo, fileType, uploadPerson, beginDate, endDate);
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("limit", limit);
        
        if (StringUtils.isNotBlank(orderNo)) {
            params.put("orderNo", orderNo);
        }
        
        if (StringUtils.isNotBlank(fileType)) {
            params.put("fileType", fileType);
        }
        
        if (StringUtils.isNotBlank(uploadPerson)) {
            params.put("uploadPerson", uploadPerson);
        }
        
        if (StringUtils.isNotBlank(beginDate)) {
            params.put("beginDate", beginDate);
        }
        
        if (StringUtils.isNotBlank(endDate)) {
            params.put("endDate", endDate);
        }
        
        List<DesignFile> recentFiles = designFileService.getRecentFiles(params);
        return Result.OK(recentFiles);
    }

    /**
     * 验证汇总单Excel文件，上传汇总单的前置动作
     */
    @AutoLog(value = "设计文件-验证汇总单Excel文件")
    @ApiOperation(value = "设计文件-验证汇总单Excel文件", notes = "验证上传的汇总单Excel文件内容是否符合要求")
    @PostMapping("/validateSummaryFile")
    public Result<SummaryFileParseResultVO> validateSummaryFile(HttpServletRequest request) {
        log.info("开始验证汇总单Excel文件");

        try {
            // 获取当前登录用户
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = loginUser != null ? loginUser.getId() : null;

            // 获取当前租户ID
            Integer tenantId = 0;
            if (loginUser != null && StringUtils.isNotBlank(loginUser.getRelTenantIds())) {
                String[] tenantIds = loginUser.getRelTenantIds().split(",");
                if (tenantIds.length > 0) {
                    try {
                        tenantId = Integer.parseInt(tenantIds[0]);
                    } catch (NumberFormatException e) {
                        log.warn("解析租户ID出错", e);
                    }
                }
            }

            // 获取订单ID
            String orderId = request.getParameter("orderId");
            if (StringUtils.isBlank(orderId)) {
                return Result.error("订单ID不能为空");
            }

            // 获取订单信息
            ProductSalesOrder productSalesOrder = productSalesOrderService.getById(orderId);
            if (productSalesOrder == null) {
                return Result.error("未找到对应的订单信息");
            }

            // 获取上传的文件
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            if (fileMap.isEmpty()) {
                return Result.error("未上传文件");
            }

            MultipartFile file = null;
            for (MultipartFile tempFile : fileMap.values()) {
                file = tempFile;
                break;
            }

            if (file == null || file.isEmpty()) {
                return Result.error("上传的文件为空");
            }

            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                return Result.error("文件名为空");
            }

            if (!fileName.toLowerCase().endsWith(".xlsx") && !fileName.toLowerCase().endsWith(".xls")) {
                return Result.error("只支持Excel文件（.xlsx或.xls）");
            }

            SysEmployee employee = sysEmployeeService.getById(userId);
            // 调用service解析Excel文件
            SummaryFileParseResultVO parseResult = designFileService.parseSummaryExcelFile(file, orderId, tenantId,employee.getWindowDoorType());

            // 如果解析失败，直接返回
            if (parseResult == null) {
                String errorMsg = parseResult != null ? parseResult.getMessage() : "解析文件失败";
                return Result.error(errorMsg);
            }

            // 解析成功，返回结果
            log.info("汇总单Excel文件验证成功，订单号: {}", parseResult.getOrderNo());
            return Result.OK(parseResult);

        } catch (Exception e) {
            log.error("验证汇总单Excel文件失败", e);
            return Result.error("验证文件失败：" + e.getMessage());
        }
    }

    /**
     * 处理并保存汇总单解析结果
     */
    @AutoLog(value = "设计文件-处理并保存汇总单解析结果")
    @ApiOperation(value = "设计文件-处理并保存汇总单解析结果", notes = "处理并保存已验证的汇总单解析结果")
    @PostMapping("/processSummaryFileResult")
    public Result<Boolean> processSummaryFileResult(HttpServletRequest request) {
        log.info("开始处理并保存汇总单解析结果");

        try {
            // 获取当前登录用户
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = loginUser != null ? loginUser.getId() : null;
            String userName = loginUser != null ? loginUser.getRealname() : null;

            // 获取订单ID
            String orderId = request.getParameter("orderId");
            if (StringUtils.isBlank(orderId)) {
                return Result.error("订单ID不能为空");
            }

            // 获取解析结果
            String parseResultJson = request.getParameter("parseResult");
            if (StringUtils.isBlank(parseResultJson)) {
                return Result.error("解析结果不能为空");
            }

            // 将JSON字符串转换为解析结果对象
            SummaryFileParseResultVO parseResult = null;
            try {
                parseResult = com.alibaba.fastjson.JSON.parseObject(parseResultJson, SummaryFileParseResultVO.class);
            } catch (Exception e) {
                log.error("解析JSON失败", e);
                return Result.error("解析结果格式错误");
            }

            // 获取上传的文件
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            if (fileMap.isEmpty()) {
                return Result.error("未上传文件");
            }

            MultipartFile file = null;
            for (MultipartFile tempFile : fileMap.values()) {
                file = tempFile;
                break;
            }

            if (file == null || file.isEmpty()) {
                return Result.error("上传的文件为空");
            }

            // 调用service处理并保存解析结果
            boolean success = designFileService.processSummaryFileResult(parseResult, orderId, file, userId, userName);

            if (success) {
                // 获取订单信息
                ProductSalesOrder order = productSalesOrderService.getById(orderId);
                
                if (order != null) {
                    productSalesOrderService.updateSummaryOrderStatus(order, userId, userName);
                }
                
                return Result.OK("汇总单解析结果保存成功");
            } else {
                return Result.error("汇总单解析结果保存失败");
            }

        } catch (Exception e) {
            log.error("处理并保存汇总单解析结果失败", e);
            return Result.error("处理失败：" + e.getMessage());
        }
    }

    /**
     * 获取型材切割方案详情
     */
    @AutoLog(value = "获取型材切割方案详情")
    @ApiOperation(value = "获取型材切割方案详情", notes = "根据订单ID和型材编码获取切割方案详情")
    @GetMapping("/getCutDetails")
    public Result<List<XingeProfileCutDetail>> getCutDetails(@RequestParam(name = "orderId") String orderId,
                                                           @RequestParam(name = "profileCode") String profileCode) {
        log.info("获取型材切割方案详情，订单ID：{}，型材编码：{}", orderId, profileCode);
        
        try {
            List<XingeProfileCutDetail> cutDetails = xingeProfileCutDetailService.getByOrderIdAndProfileCode(orderId, profileCode);
            return Result.OK(cutDetails);
        } catch (Exception e) {
            log.error("获取型材切割方案详情失败", e);
            return Result.error("获取切割方案详情失败：" + e.getMessage());
        }
    }

    /**
     * 提交订单进行审核
     */
    @AutoLog(value = "成品销售订单-提交审核")
    @ApiOperation(value = "成品销售订单-提交审核", notes = "将已上传优化单的订单提交审核")
    @PostMapping(value = "/submitForReview")
    public Result<?> submitForReview(@RequestParam(name = "orderId") String orderId) {
        log.info("提交订单审核, orderId={}", orderId);

        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String operatorId = loginUser != null ? loginUser.getId() : null;

        // 查询订单信息
        String[] orderIdArray = orderId.split(",");
        boolean success = true;
        ArrayList<String> orderNoList = new ArrayList<>();
        for (String id : orderIdArray) {
            ProductSalesOrder order = productSalesOrderService.getById(id);
            if (order == null) {
                log.error("订单不存在, orderId={}", id);
                return Result.error("订单不存在");
            }else {
                orderNoList.add(order.getOrderNo());
            }

            // 检查订单状态
            if (order.getStatus() != 3) { // 只有已上传优化单的状态才能提交审核
                log.error("订单状态不正确, orderId={}, status={}", id, order.getStatus());
                return Result.error("只有已上传优化单的订单才能提交审核");
            }

        }

        if (success) {
            log.info("订单提交审核成功, orderId={}", orderId);

            //提交审核成功 保存领料表信息
            productSalesOrderService.saveRequisitionInfo(orderId,orderNoList);
            
            // 计算并更新订单总成本
//            for (String id : orderIdArray) {
//                try {
//                    BigDecimal totalCost = productSalesOrderService.calculateAndUpdateOrderTotalCost(id);
//                    log.info("订单成本计算完成, orderId={}, totalCost={}", id, totalCost);
//                } catch (Exception e) {
//                    log.error("订单成本计算失败, orderId={}, error={}", id, e.getMessage(), e);
//                    // 成本计算失败不影响订单提交审核的主流程，只记录日志
//                }
//            }
            
            return Result.OK("订单提交审核成功");
        } else {
            log.error("订单提交审核失败, orderId={}", orderId);
            return Result.error("订单提交审核失败");
        }
    }
} 